package org.lagou.threadpool;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author junbao
 */
public class WatchingThreadPool extends FixedThreadPool implements Runnable{

    private static final Logger LOGGER = LoggerFactory.getLogger(WatchingThreadPool.class);

    // 定义线程池使用的阈值
    private static final double ALARM_PERCEMT = 0.90;

    private final Map<URL, ThreadPoolExecutor> THREADPOOLS = new ConcurrentHashMap<>();

    public WatchingThreadPool() {
        // 每个3秒打印线程使用情况
        Executors.newSingleThreadScheduledExecutor()
                .scheduleWithFixedDelay(this, 1, 3, TimeUnit.SECONDS);
    }

    // 通过父类创建线程池
    @Override
    public Executor getExecutor(URL url) {
        final Executor executor = super.getExecutor(url);
        if(executor instanceof ThreadPoolExecutor){
            THREADPOOLS.put(url,(ThreadPoolExecutor) executor);
        }
        return executor;
    }


    @Override
    public void run() {
        // 遍历线程池
        for(Map.Entry<URL, ThreadPoolExecutor> entry : THREADPOOLS.entrySet()) {
            final URL url = entry.getKey();
            final ThreadPoolExecutor executor = entry.getValue();
            // 计算相关指标
            final int activeCount = executor.getActiveCount();
            final int poolSize = executor.getCorePoolSize();
            double usePercent = activeCount / (poolSize*1.0);
            LOGGER.info("\"线程池执行状态:[{}/{}]:{}%",activeCount,poolSize,usePercent);
            if(usePercent > ALARM_PERCEMT) {
                LOGGER.error("超出警戒值！host:{}, 当前已使用量:{}%, URL:{}",url.getIp(),usePercent,url);
            }
        }

    }
}
